package com.warmheart.core.pool;

import java.util.HashMap;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.warmheart.core.ex.ServerException;
import com.warmheart.core.util.UUIDGenerator;

/**
 * 
 * @ClassName: PoolTaskUtil
 * @Description: 多线程执行工具类
 * @author ZhangJianyang
 * @date 2025-06-16 09:37:02
 *
 */
public class PoolRunUtil {

    protected PoolRunUtil() {
    }

    public static PoolRunUtil.RunBuilder custom() {
        return new RunBuilder();
    }

    public static class RunBuilder {

        private Map<String, WhRunnable> runnableMap;

        private ThreadPoolTaskExecutor threadPoolTaskExecutor;

        private RunBuilder() {
        }

        /**
         * 
         * @Title: put
         * @Description: 添加不包含返回值的执行逻辑
         * @author ZhangJianyang
         * @param runnable
         *            执行逻辑
         * @param remarks
         *            任务备注
         * @return
         */
        public RunBuilder put(Runnable runnable, String remarks) {
            if (runnableMap == null) {
                runnableMap = new HashMap<String, WhRunnable>();
            }
            String currKey = "runKey" + UUIDGenerator.getUUID();
            runnableMap.put(currKey, new WhRunnable(remarks, runnable));
            return this;
        }

        /**
         * 
         * @Title: pool
         * @Description: 执行线程池（如果不设置 ，则默认使用MdcThreadPoolTaskExecutor）
         * @author ZhangJianyang
         * @param threadPoolTaskExecutor
         *            线程池
         * @return
         */
        public RunBuilder pool(@NotNull ThreadPoolTaskExecutor threadPoolTaskExecutor) {
            this.threadPoolTaskExecutor = threadPoolTaskExecutor;
            return this;
        }

        /**
         * 
         * @Title: run
         * @Description: 执行逻辑（该方法只执行逻辑，不进行阻塞等待）
         * @author ZhangJianyang
         * @throws ServerException
         */
        public void excute() throws ServerException {
            PoolOper.custom(this.runnableMap, this.threadPoolTaskExecutor).build().run();
        }

        /**
         * 
         * @Title: waitFor
         * @Description: 执行逻辑并等待执行完成（该方法会进行阻塞等待，该方法完成后，所有线程逻辑均执行完毕）
         * @author ZhangJianyang
         * @return
         * @throws ServerException
         */
        public void waitFor() throws ServerException {
            PoolOper.custom(this.runnableMap, this.threadPoolTaskExecutor).build().waitFor();
        }

    }
}
